package com.moonbird.springboot.service;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.moonbird.springboot.DTO.faceDTO;
import com.moonbird.springboot.Utils.face.FileUtil;
import com.moonbird.springboot.Utils.face.HttpUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Service
public class FaceService {
    // webapi 接口地址
    private static final String URL3 = "http://tupapi.xfyun.cn/v1/expression";
    // 人脸特征分析年龄webapi 接口地址
    private static final String URL1 = "http://tupapi.xfyun.cn/v1/age";
    // webapi 接口地址
    private static final String URL2 = "http://tupapi.xfyun.cn/v1/sex";
    private static final String URL0 = "http://tupapi.xfyun.cn/v1/face_score";
    private static final String APPID = "f9173867";
    private static final String API_KEY = "19920808a7c387f8263b259c3dbf1077";
    private static String IMAGE_NAME = "";
    private static String filePath = "";

    public faceDTO analyzeFaceAndGetScore(MultipartFile file) throws UnsupportedEncodingException {
        IMAGE_NAME = file.getOriginalFilename().split("\\.")[0];
        byte[] imageData = null;
        try {
            imageData = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            String fileName = IMAGE_NAME + ".jpg";
            filePath = "src/main/resources/static/image/" + fileName;
            Files.write(Paths.get(filePath), imageData);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, String> header = buildHttpHeader();
        byte[] imageByteArray;
        try {
            imageByteArray = FileUtil.read(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String result = HttpUtil.doPost1(URL0, header, imageByteArray);
        String result1 = HttpUtil.doPost1(URL1, header, imageByteArray);
        result1 = dealResult(result1);

        String result2 = HttpUtil.doPost1(URL2, header, imageByteArray);
        result2 = dealResult1(result2);

        String result3 = HttpUtil.doPost1(URL3, header, imageByteArray);
        result3 = dealResult2(result3);

        // Delete the saved image file
        deleteImageFile(filePath);

        // 解析结果并获取评分
        String score = parseScoreFromResult1(result);
        if (score.equals("0")){
            score = "漂亮";
        }else if (score.equals("1")){
            score = "好看";
        }else if (score.equals("2")){
            score = "普通";
        }else if (score.equals("3")){
            score = "难看";
        }else if (score.equals("4")){
            score = "其他";
        }else if (score.equals("5")){
            score = "半人脸";
        }else if (score.equals("6")){
            score = "多人";
        }
        faceDTO facedto= new faceDTO();
        facedto.setScore(score);
        facedto.setAge(result1);
        facedto.setGender(result2);
        facedto.setExpression(result3);
        if (facedto.getScore().equals("其他")){
            facedto.setScore("非人脸");
            facedto.setAge("非人脸");
            facedto.setGender("非人脸");
            facedto.setExpression("非人脸");
        }
        return facedto;
    }

    private void deleteImageFile(String filePath) {
        try {
            Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String dealResult2(String result) {
        System.out.println("===================================================");
        System.out.println("处理表情:"+result);

        result = parseScoreFromResult1(result);
        System.out.println("表情指标：" + result);
        System.out.println("===================================================");
        if (result.equals("0"))	{
            result = "非人脸";
        }else if (result.equals("1")) {
            result = "其他表情";
        }else if (result.equals("2")) {
            result = "喜悦";
        }else if (result.equals("3")){
            result = "愤怒";
        }else if (result.equals("4")){
            result = "悲伤";
        }else if (result.equals("5")){
            result = "惊恐";
        }else if (result.equals("6")) { // 6 代表多人
            result = "厌恶";
        }else if (result.equals("7")){
            result = "中性";
        }
        return result;
    }

    private String dealResult1(String result) {
        System.out.println("===================================================");
        System.out.println("处理性别:"+result);

        result = parseScoreFromResult1(result);
        System.out.println("性别指标：" + result);

        System.out.println("===================================================");
        if (result.equals("0"))	{
            result = "男";
        }else if (result.equals("1")) {
            result = "女";
        }else if (result.equals("2")) {
            result = "难以辨别";
        }else if (result.equals("3")){
            result = "多人";
        }else if (result.equals("4")){
            result = "其他";
        }
        return result;
    }

//    private static String parseScoreFromResult1(String result) {
//        // 解析 result 字符串，提取评分
//        try {
//            // 假设使用 JSON 解析工具，例如 Jackson 或 Gson
//            // 这里用简单的字符串处理来示例
//            // 实际中应该使用 JSON 库来解析 JSON 字符串
//            System.out.println(result);
//            String rateStr = result.substring(result.indexOf("\"label\":") + 8, result.indexOf(",\"name\":"));
//            System.out.println("==================");
//            System.out.println(rateStr);
//            System.out.println("==================");
//            return rateStr;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "4"; // 解析失败时返回默认值或者抛出异常
//        }
//    }

    private static String parseScoreFromResult1(String result) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
        JsonElement labelElement = jsonObject.getAsJsonObject("data").getAsJsonArray("fileList").get(0).getAsJsonObject().get("label");
        if (labelElement != null && labelElement.isJsonPrimitive()) {
            return labelElement.getAsString();
        }
        return "未知"; // 如果 "label" 不存在或不是字符串，则返回默认值
    }

    private static String parseScoreFromResultage(String result) {
        // 解析 result 字符串，提取评分
        try {
            // 假设使用 JSON 解析工具，例如 Jackson 或 Gson
            // 这里用简单的字符串处理来示例
            // 实际中应该使用 JSON 库来解析 JSON 字符串
            System.out.println(result);
            String rateStr = result.substring(result.indexOf("\"label\":"), result.indexOf(",\""));
            System.out.println("===================================================");
            System.out.println(rateStr);
            System.out.println("===================================================");
            return rateStr;
        } catch (Exception e) {
            e.printStackTrace();
            return "4"; // 解析失败时返回默认值或者抛出异常
        }
    }

    private String dealResult(String result) {
        System.out.println("===================================================");
        System.out.println("处理年龄");
        result = parseScoreFromResult1(result);
        System.out.println("年龄指标："+ result);
        System.out.println("===================================================");
        if (result.equals("0"))	{
            result = "0-1岁";
            System.out.println("0-1岁");
        }else if (result.equals("1")) {
            result = "2-5岁";
            System.out.println("2-5岁");
        }else if (result.equals("2")) {
            result = "6-10岁";
            System.out.println("6-10岁");
        }else if (result.equals("3")){
            result = "11-15岁";
            System.out.println("11-15岁");
        }else if (result.equals("4")){
            result = "16-20岁";
            System.out.println("16-20岁");
        }else if (result.equals("5")){
            result = "21-25岁";
            System.out.println("21-25岁");
        }else if (result.equals("6")) {
            result = "31-40岁";
            System.out.println("31-40岁");
        }else if (result.equals("7")){
            result = "41-50岁";
            System.out.println("41-50岁");
        }else if (result.equals("8")){
            result = "51-60岁";
            System.out.println("51-60岁");
        }else if (result.equals("9")) {
            result = "61-80岁";
            System.out.println("61-80岁");
        }else if (result.equals("10")){
            result = "80岁以上";
            System.out.println("80岁以上");
        }else if (result.equals("11")){
            result = "其他";
            System.out.println("其他");
        }else if (result.equals("12")) {
            result = "26-30岁";
            System.out.println("26-30岁");
        }
        return result;
    }

//    private String parseScoreFromResult(String result) {
//        // 解析 result 字符串，提取评分
//        try {
//            // 假设使用 JSON 解析工具，例如 Jackson 或 Gson
//            // 这里用简单的字符串处理来示例
//            // 实际中应该使用 JSON 库来解析 JSON 字符串
//            String rateStr = result.substring(result.indexOf("\"label\":") + 8, result.indexOf(",\"name\":"));
//            return rateStr;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "4"; // 解析失败时返回默认值或者抛出异常
//        }
//    }

    private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"image_name\":\"" + IMAGE_NAME + "\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", APPID);
        return header;
    }
}
